const express = require('express')
const router = express.Router()
const articlesDao = require('../database/articlesDao')
// 根据文章id获取文章
// 统一响应格式
const formatResponse = (data, msg = '成功') => {
  return {
    code: 200,
    msg,
    data: Array.isArray(data) ? data : [data].filter(Boolean)
  };
};

// 获取全部文章
router.get('/getAllArticles', async (req, res) => {
  try {
    const data = await articlesDao.getAllArticle();
    res.json(formatResponse(data));
  } catch (err) {
    console.error('Controller错误:', err);
    res.status(500).json({
      code: 500,
      msg: '服务器内部错误',
      data: null
    });
  }
});

// 获取文章详情
router.get('/getArticlesByID', async (req, res) => {
  try {
    const { id } = req.query;
    if (!id) throw new Error('缺少文章ID参数');

    const data = await articlesDao.getArticleWithAuthor(id);
    if (!data) {
      return res.status(404).json({
        code: 404,
        msg: '文章不存在',
        data: null
      });
    }

    res.json(formatResponse(data));
  } catch (err) {
    res.status(400).json({
      code: 400,
      msg: err.message,
      data: null
    });
  }
});
// 新增文章
router.post('/addArticles', async (req, res) => {
  try {
    const { title, content, author_id } = req.body
    const result = await articlesDao.addArticle(title, content, author_id)
    res.send({
      code: 200,
      msg: '新增文章成功',
      data: result
    })
  } catch (err) {
    res.status(500).json({
      code: 500,
      msg: '服务器错误: ' + err.message,
      data: null
    });
  }
})
// 添加点赞数
router.put('/addLikes', async (req, res) => {
  try {
    let id = req.body.id
    let result = await articlesDao.addLikes(id)
    res.send({
      code: 200,
      msg: '获取成功',
      data: result
    })
  } catch (err) {
    res.send({
      code: 400,
      msg: '获取失败',
      data: err
    })
  }
})
module.exports = router